#!/usr/bin/env python
# -*-coding:utf-8-*-

import requests
import json
import sys
import urllib
import hashlib
from Crypto.Cipher import AES
import os
import base64
from pysqlite3 import DbHelper

reload(sys)
sys.setdefaultencoding("utf-8")

g_host = 'http://api.713jk3.cn'
g_session = requests.session()
g_db = DbHelper('qiezivideo.db')

g_headers = {
    'User-Agent': 'okhttp/3.9.0',
    'Accept-Encoding': 'gzip',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    "Connection": "keep-alive",
    "Accept" : "*/*",
    "once": "727260",
    "HTTP-X-TOKEN": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3d3cuYmFpZHUuY29tIiwiYXVkIjoid3d3LmJhaWR1LmNvbSIsImlhdCI6MTU0NjU3NDY1NiwibmJmIjoxNTQ2NTc0NjU1LCJleHAiOjE1NDkxNjY2NTYsImRhdGEiOnsidG9rZW4iOiJGRzh5R1doRUpIeXdjR2VGVDU0WngyS0hZYlI4UEhQUFk0elwvMGpkRytnSHNDaWh2YzkrbTd5UlwvTjFFdkFZVjkifX0.geIEdi9k7mzFAD0KFdgpC1FOSVTh5uGuozDBjqEx68I"
}

def getmd5(md5str):
    m1 = hashlib.md5()
    m1.update(md5str.encode("utf-8"))
    return m1.hexdigest()

def getSortStr(parmsets):
    keys = sorted(parmsets)
    v=''
    for key in keys:
        if(v != ''):
            v+='&'
        v+=key
    return v


def getsign(parm, once):
    parmlist = parm.split('&')
    sortstr = getSortStr(parmlist)
    md5str = '%d%s'%(once, sortstr)
    sign = getmd5(md5str)
    md5str = sign[0:8] + sign
    return getmd5(md5str)



def aes_decode(data, key, iv):
    unpad = lambda s : s[0:-ord(s[-1])]
    
    cipher = AES.new(key, AES.MODE_CBC, iv)
    result2 = base64.b64decode(data)
    decrypted = unpad(cipher.decrypt(result2))
    return  decrypted  

def md5(s):
    m = hashlib.md5()
    m.update(s.encode("utf-8"))
    return m.digest()

def decode(content, key):
    key = md5(key)
    iv = md5('c75f235d2d302205')
    return aes_decode(content, key, iv)

def commonrequest(uri, parm):
    once = 516142
    url= g_host + uri + '?' + parm
    sign = getsign(parm, once)
    g_headers['sign'] = sign
    g_headers['once'] = str(once)
    while True:
        try:
            res = g_session.get(url, headers=g_headers)
            break
        except Exception as e:
            print(e)
    return decode(res.content, res.headers['q-code'])

#decode('gHXJ8J/vSDTBImpWSaevgVPiWh8kK9gOZ+awzW3oT7NCfpJhtN0iLDuaDFpP+81QCpK0+ccPAZwpo8IEhj1PcVyz4p4gr/JS3U5bJgi5zHIR3aVQ3qPyZ88bDoI1+Tdp4W3TTajhLfkZumc5rB3VHLfYhEkN4H5FteOQKNjvI4WB4TwM8dOLe4TgJtKiY51/W+mottB+FZpKbFYqVRuBuZ8fyDMETmzKn/ObBck6UOWr6inJOJ9bNC/g5VF4DFYzQpd/PBVvZN+RH50LARB2W/8qFVBRqKSUoZDXnprooxLWpDjX+iw+AvJbFxUbjYhiCLDqNJrg+BW7AMkR1abeHmYweII6tabQajfpcYmWWPYbUUqsq7fzDX5PrUNiG/KXinyv7bL5mcj4vQJfFFIKVPmd9M1NXqN2zzMvJ0Tk5Fvjv16IGmvBIqvqaIZr/M36CsLxUQLch4WvUnMM4Va48G5vES/wpC8/2wvn+XNbySHbiduqtMQvwHQl9NQrooZTFTEIoegfnk87hJmjY5JtJUMNCFtCVSkczOAz93S2umXEuZGe/tK5TnvshMkLf7bfav25lKUsHQ7NEHTI5atQ+HiyecfmvrVc66MCNNBfG/f6Raa9phJYB5xonJTYaLnrEzAfWSQqMEeXUP4aBchOkIRROgVxzcPUNi2zj0XxYhVCHxkQ/beNZlxC3GpNHFH0Zf1yCPZDWQ+Ofhu3n9LVv0uRHqwGgyBJZ1cjYyLeXEdAbO/XFPjdCyISoGvr8DI8vNqQAKlJC/MMEf595BaSpU+axrSyhr9cdHMQ2T+c6+k2Q/cnPKFsGhPDp1nOViA8HbH2Is5xWvZ6uBTP3wPvlq2Vo68B88BaA6bs8A/hY/fJOL5o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1bcRFhaUdkPGZmdQ/cW+VgJuh3xkAL8GFWQMUzvxVQwrg6dUYH/ReOXLeXrTjxENyHaT3TZiyNfklBjSPgEUuNxAOUyrvUmxLA+4bBbRhYlF1qeH9mmK+EFgczy4XkAz3cNaYpb+emZzFXV1IqvuewU8nDh+d2SYkdxgJoBmloYmo/QymA3oGOcz9uTQj0wpQBNDoW3mMgQdVWZDvZiSLsxm8xXJvO3oSSGCpnLr4+bgz6Um0e7VDP9x0CnOn+AY0Hj0T2aLAomOX3BrBVjwMxUadrmkXiUUz9EtKtJlTSrSgQurG6Vp2uo7rm3C9Ixo6Eg6plN7WOLMjYndfCTHct62o4b3g13dmBeIEexEPex/Rzsmz33U3h7EeVtwgN3qA3c4XT6/9GX2Z1zmbByLkAcLTI4UOM4+2v6Y7I9bOuTpA27a2hGU+c7wY+9tlhIFUFSh/2S0BZrxCLhjUmOjM0DMXRPD99ZVJI8VpvlvUtiRjfZH+lFKW1XdY3pkwTI2AtcidTodyxzJHEhhQwp29x5st8HfJZJjufkeHD5BAC0nuNvXhrQmVi1AI0I=', '364c5126536b2383')


def zoneCategorys(zone_id, page, pagesize):
    '''
    @zone_id, @page, @pagesize
    '''
    uri = '/api/Video/zoneCategorys'
    parm = 'zone_id=%d&page=%d&pageSize=%d'%(zone_id, page, pagesize)
    content = commonrequest(uri, parm)
    g_db.insertzoneCategorys(content)



def detail(id):
    '''string id'''
    uri = '/api/Video/detail'
    parm = 'video_id=%s'%(id)
    content = commonrequest(uri, parm)
    print(content)
    j = json.loads(content)
    if(j['code'] == 405):
        print('视频不存在')
        return '视频不存在','',''
    urls = j['data']['urls']
    picurl = j['data']['cover_img']
    for r,l in urls.items():
        if l != '':
            if(j['data']['source_url'][0] == None):
                return j['data']['summary'], 'http://v.5151mmy.com/' + l,picurl
            else:
                return j['data']['summary'], j['data']['source_url'][0] + l,picurl
    return j['data']['summary'], '', picurl

def dealcommonvideolist(content):
    j = json.loads(content)
    data = j['data']['data']
    for item in  data:
        sum=''
        url=''
        if g_db.insertAVideo(item, url, sum):
            #sum,url = detail(item['id'])
            content = "%s\n%s\n%s\n\n"%(item['title'], item['cover_img'], url)
            print(content)
    pagecount = int(j['data']['pagedata']['pagecount'])
    return pagecount > 0 and page < pagecount

#7.55
def filtervideo2(cat_id, page):
    '''
    cat_id, page
    '''
    uri = '/api/Video/filtervideo'
    parm = 'cat_id=%d&page=%d'%(cat_id, page)
    content = commonrequest(uri, parm)
    #print(content)
    return dealcommonvideolist(content)

def filtervideo(type, zoneid, cat_id, page):
    '''
    type, zoneid, cat_id, page
    '''
    uri = '/api/Video/filtervideo'
    parm = 'type=%d&zoneid=%d&cat_id=%d&page=%d'%(type, zoneid, cat_id, page)
    content = commonrequest(uri, parm)
    print(content)
    return dealcommonvideolist(content)

def slug(type):
    uri='/api/Video/slugs'
    parm='type=%d'%(type)
    content = commonrequest(uri, parm)
    #print(content)
    g_db.insertslug(content)

'''
type is:create_at,sort_num,play_num
donot use it
'''
def videos(type, page):
    uri='/api/Video/videos'
    parm = 'type=%s&page=%d'%(type, page)
    content = commonrequest(uri, parm)
    print(content)

def categoryvideos(page):
    '''
    int page
    '''
    uri='/api/Video/categoryvideos'
    parm='slug_id=&identify=cat_small&page=%d&pageSize=10'%(page)
    content = commonrequest(uri, parm)
    #print(content)
    return dealcommonvideolist(content)
    

if __name__ == '__main__':
    '''
    for i in range(0, 3):
        zoneCategorys(0, i, 20)

    detail('490')

    for i in range(1,3):
        slug(i)

    page = 1
    hasNext = True
    while hasNext:
        hasNext = categoryvideos(page)
        page += 1

    '''

    types = g_db.gettypes()

    for catid in types:
        page = 1
        hasNext = True
        while hasNext:
            print('catid=%d'%(catid))
            hasNext = filtervideo2(catid, page)
            page+=1

